<?php

namespace App\Http\Controllers\Purchase;

use App\Http\Controllers\BaseController;
use App\Http\Validate\Purchase\PurchasePayOrderNew as PurchasePurchasePayOrderNew;
use App\Models\Purchase\PurchasePayOrderNew;
use App\Models\Purchase\PurchasePayOrderNewSub;
use App\Models\Purchase\PurchaseWarehousingOrderwithpay;
use App\Services\Balance\Balance;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

/**
 * 付款列表
 */
class PurchasePayOrderNewController extends BaseController
{
    /**
     * 付款列表
     */
    public function getorderlist(Request $request)
    {

        $cpid = $this->mangerinfo['cpid'];
        $manger_id = $this->mangerinfo['id'];
        if ($this->mangerinfo['utype'] == 4) {
            $manger_id = 0; //查询所有订单
        }
        $list = PurchasePayOrderNew::getList($request, $cpid, $manger_id);
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $list]);
    }

    /**
     * 审核取消
     */
    public function doauditcancel(Request $request)
    {

        $id = $request->id;
//        $ids = is_array($ids) ? $ids : (is_array(json_decode($ids, true)) ? json_decode($ids, true) : []);

        $cpid = $this->mangerinfo['cpid'];
        $manger_id = $this->mangerinfo['id'];

        $payorderinfo = PurchasePayOrderNew::where([
            'id' => $id,
            'cpid' => $cpid,
        ])->first();

        if(empty($payorderinfo))
        {
            return response()->json(['code' => '001', 'msg' => '订单不存在']);
        }
        if($payorderinfo->audit_status >2)
        {
            return response()->json(['code' => '001', 'msg' => '订单状态不能撤审']);
        }
        $approvalinfo = DB::table('order_approvals')
            ->where([
                'order_id'=>$id,
                'type'=>'purchase_pay_order_new',
            ])
            ->orderBy('id','desc')
            ->first();

        DB::beginTransaction();
        try {
            //
            PurchasePayOrderNew::where([
                'id' => $id,
                'cpid' => $cpid,
                'manger_id' => $manger_id,
            ])->update( ['audit_status' => 5]);
            DB::table('order_approvals')
                ->where([
                    'order_id'=>$id,
                    'type'=>'purchase_pay_order_new',
                    'id'=>$approvalinfo->id,
                ])
                ->update(['is_completed'=>1,'current_step_id'=>0]);
            DB::table('approval_histories')
                ->insert([
                    'order_id'=>$id,
                    'type'=>'purchase_pay_order_approve',
                    'step_id'=>$approvalinfo->current_step_id,
                    'approver_id'=>0,
                    'status'=>'revoked',
                ]);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '审核取消操作失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '补货单审核取消成功']);
    }

    /**
     * 审核通过
     */
    public function doauditsuccess(Request $request)
    {

        $id = $request->id;
//        $ids = is_array($ids) ? $ids : (is_array(json_decode($ids, true)) ? json_decode($ids, true) : []);

        $cpid = $this->mangerinfo['cpid'];
        $manger_id = $this->mangerinfo['id'];

        $payorderinfo = PurchasePayOrderNew::where([
            'id' => $id,
            'cpid' => $cpid,
        ])->first();
        if(empty($payorderinfo))
        {
            return response()->json(['code' => '001', 'msg' => '订单不存在']);
        }
        if(($payorderinfo->audit_status == 1 && $payorderinfo->approve_id1 != $manger_id ) || ($payorderinfo->audit_status == 2 && $payorderinfo->approve_id2 != $manger_id ))
        {
            return response()->json(['code' => '001', 'msg' => '没有操作权限']);
        }
        $approvalinfo = DB::table('order_approvals')
            ->where([
                'order_id'=>$id,
                'type'=>'purchase_pay_order_new',
            ])
            ->orderBy('id','desc')
            ->first();
        //查询下一级审批
        $approval_nextStep = DB::table('approval_steps')
            ->where('flow_id','=',1)
            ->where('step_order','>',$approvalinfo->current_step_id)
            ->orderBy('step_order','asc')
            ->first();

        DB::beginTransaction();
        try {
            //
            if($approval_nextStep)
            {
                DB::table('order_approvals')
                    ->where('id','=',$approvalinfo->id)
                    ->update(['current_step_id'=>$approval_nextStep->step_order]);
                // 更新订单审批状态
                PurchasePayOrderNew::where('id','=',$approvalinfo->id)
                    ->update(['audit_status'=>2]);
            }else{
                // 所有步骤已完成
                DB::table('order_approvals')
                    ->where('id','=',$approvalinfo->id)
                    ->update(['is_completed'=>1]);
                // 更新订单审批状态
                PurchasePayOrderNew::where('id','=',$approvalinfo->id)
                    ->update(['audit_status'=>3]);

                //审批通过后增加付款单
                $datawp = [
                    'cpid' => $cpid,
                    'manger_id' => $manger_id,
                    'type' => 2,
                    'pay_money' => $payorderinfo->pay_money,
                    'pay_sn_code' => $payorderinfo->pay_sn_code,
                    'create_at' => time(),
                    'update_at' => time(),
                ];
                PurchaseWarehousingOrderwithpay::create($datawp);

                //增加供应商余额变化

                //
            }
            //审批记录
            DB::table('approval_histories')
                ->insert([
                    'order_id'=>$id,
                    'type'=>'purchase_pay_order_approve',
                    'step_id'=>$approvalinfo->current_step_id,
                    'approver_id'=>$manger_id,
                    'status'=>'approved',
                ]);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '审核取消操作失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '补货单审核取消成功']);
    }

    public function doauditrefuse(Request $request)
    {
        $id = $request->id;

        $cpid = $this->mangerinfo['cpid'];
        $manger_id = $this->mangerinfo['id'];

        $payorderinfo = PurchasePayOrderNew::where([
            'id' => $id,
            'cpid' => $cpid,
        ])->first();
        if(empty($payorderinfo))
        {
            return response()->json(['code' => '001', 'msg' => '订单不存在']);
        }
        if(($payorderinfo->audit_status == 1 && $payorderinfo->approve_id1 != $manger_id ) || ($payorderinfo->audit_status == 2 && $payorderinfo->approve_id2 != $manger_id ))
        {
            return response()->json(['code' => '001', 'msg' => '没有操作权限']);
        }
        $approvalinfo = DB::table('order_approvals')
            ->where([
                'order_id'=>$id,
                'type'=>'purchase_pay_order_new',
            ])
            ->orderBy('id','desc')
            ->first();

        DB::beginTransaction();
        try {

            // 所有步骤已完成
            DB::table('order_approvals')
                ->where('id','=',$approvalinfo->id)
                ->update(['is_completed'=>1]);
            // 更新订单审批状态
            PurchasePayOrderNew::where('id','=',$approvalinfo->id)
                ->update(['audit_status'=>4]);

            //审批记录
            DB::table('approval_histories')
                ->insert([
                    'order_id'=>$id,
                    'type'=>'purchase_pay_order_approve',
                    'step_id'=>$approvalinfo->current_step_id,
                    'approver_id'=>$manger_id,
                    'status'=>'approved',
                ]);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '审核取消操作失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '补货单审核取消成功']);
    }

    /**
     * 获取付款单详情
     *
     */
    public function getinfo(Request $request)
    {
        $cpid = $this->mangerinfo['cpid'];
        $manger_id = $this->mangerinfo['id'];
        $id = $request->id ?? 0;
        $info = PurchasePayOrderNew::where(['cpid' => $cpid, 'is_del' => 1, 'id' => $id])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '无效参数']);
        }

        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => ['info' => $info->toArray()]]);
    }

    public function getinfobypaysncode(Request $request){
        $cpid = $this->mangerinfo['cpid'];
        $manger_id = $this->mangerinfo['id'];
        $pay_sn_code = $request->pay_sn_code ?? '';
        $info = PurchasePayOrderNew::where(['cpid' => $cpid, 'is_del' => 1, 'pay_sn_code' => $pay_sn_code])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '无效参数']);
        }

        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => ['info' => $info->toArray()]]);
    }

    /**
     * 办款操作
     */

    public function dopayrealmoney(Request $request)
    {
        $req_data = $request->only([
            'id', 'pay_money', 'pay_at', 'screenshot_file', 'remark'
        ]);

        $Validate = new PurchasePurchasePayOrderNew();
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }

        $cpid = $this->mangerinfo['cpid'];
        $manger_id = $this->mangerinfo['id'];
        if ($this->mangerinfo['utype'] == 8) {//会计办款
            $info = PurchasePayOrderNew::where(['cpid' => $cpid, 'is_del' => 1, 'id' => $req_data['id']])->first();
        }else{//是否需要限制只能会计办款？
            // return response()->json(['code' => '001', 'msg' => '无权限']);
            $info = PurchasePayOrderNew::where(['cpid' => $cpid, 'is_del' => 1, 'id' => $req_data['id']])->first();
        }




        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '无效参数']);
        }

        if ($info->audit_status != 3) {
            return response()->json(['code' => '001', 'msg' => '审核成功方可付款']);
        }

        $pay_at = isset($req_data['pay_at']) ? ((strtotime($req_data['pay_at']) > 0) ? strtotime($req_data['pay_at']) : intval($req_data['pay_at'])) : 0;
        // echo $req_data['pay_money'];exit;
        $data = [
            'pid' => $req_data['id'],
            'pay_money' => $req_data['pay_money'],
            'pay_at' => $pay_at,
            'screenshot_file' => $req_data['screenshot_file'],
            'remark'=>strval($req_data['remark']),
            'create_at' => time(),
            'update_at' => time(),
        ];

        //写入入库付款对账表
        // $datawp=[
        //     'cpid'=>$cpid,
        //     'manger_id'=>$info->manger_id,
        //     'type'=>2,
        //     'pay_money'=>$req_data['pay_money'],
        //     'create_at' => time(),
        //     'update_at' => time(),
        // ];

        DB::beginTransaction();
        try {
            //更新付款记录
            PurchasePayOrderNewSub::create($data);
            //更新实际付款金额
            PurchasePayOrderNew::where(['cpid' => $cpid, 'manger_id' => $manger_id, 'is_del' => 1, 'id' => $req_data['id']])->increment('pay_money_real', $data['pay_money']);
            //写入入库付款对账表
            // PurchaseWarehousingOrderwithpay::create($datawp);

            //更新供应商余额
            Balance::purchaseRecharge($info->custom_id,$cpid,$req_data['pay_money'],$this->mangerinfo['id']);

            DB::commit();
        } catch (\Exception $e) {

            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => $e->getMessage()]);
        }

        return response()->json(['code' => '000', 'msg' => '办款成功']);
    }


    /**
     * 入库付款对账表
     */
    public function getwarehousingorderwithpay(Request $request)
    {

        $cpid = $this->mangerinfo['cpid'];
        $manger_id = $this->mangerinfo['id'];
        if ($this->mangerinfo['utype'] == 4) {
            $manger_id = 0; //查询所有订单
        }
        $list = PurchaseWarehousingOrderwithpay::getList($request, $cpid, $manger_id);
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $list]);
    }
}
